<template>

    <!-- 添加或修改advertise对话框 -->
    <el-dialog v-model="open" :title="form.id?'修改数据':'新增数据'" width="500px" append-to-body >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="学科名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入学科名称" />
            </el-form-item>

             <el-form-item label="学科说明" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入广告链接" />
            </el-form-item>

            <el-form-item label="imagePath" prop="imagePath">
               
                <el-upload
                    class="avatar-uploader"
                    :action="imageUploadUrl" 
                    :data="imageParams.ossdata"
                    name="imgFile"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="form.imagePath" :src="form.imagePath" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
            </el-form-item>

            <el-form-item label="状态" prop="status">
                 <el-radio-group v-model="form.status">
                     <template  v-for="item in sys_normal_disable" :key="item.value">
                        <el-radio  :label="item.value">{{item.label}}</el-radio>
                     </template>
                </el-radio-group>
            </el-form-item>
            


        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup="Advertise">
    import { reactive, ref,getCurrentInstance, ComponentInternalInstance  } from 'vue'
    import { type FormRules, type FormInstance, ElMessage } from 'element-plus';
    // TypeScript数据模型，约束只能传变量
    import {  SubmitForm,RespModel } from '@/api/app/typescript/subjectModel';
    // 引用后台的api-查询详情、新增、修改
    import { getSubject,addSubject,updateSubject } from '@/api/app/subject/subject';

    // 获取当前vue3的页面this对象转换为proxy代理，查询 sys_dict_data表中的值
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { sys_normal_disable } = proxy!.useDict('sys_normal_disable');

    const open = ref(false);
    //得到数据表单form样式对象
    const formRef = ref<FormInstance>();

    //声明子组件的自定义事件 https://cn.vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
    const emit = defineEmits(['refreshDataList'])

    
//图片上传地址
const imageUploadUrl =ref(import.meta.env.VITE_APP_BASE_API+'/oss/uploadImg');

//配置请求头的令牌


//自己的定义额外参数
const imageParams = reactive({ 
    ossdata: {
        fatherPath:'images'
    }
});


   // 定义表单对象
   const form = ref<SubmitForm>({
       id: undefined,
       name: '',
       remark: '',
       imagePath: '',
       status: '0'

   });

   // 表单验证
   const rules = reactive<FormRules>({
        name: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
       remark: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
       imagePath: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
       status: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
   });

   //对话框保存按钮
   const submitForm = () => {
     formRef.value.validate((valid: boolean) => {
           //验证不成功
       	if (!valid) {
       		return false
       	}

        //修改
        if(form.value.id){
            updateSubject(form.value).then(resp=>{
                 ElMessage.success({
                        message: '修改成功',
                        duration: 500,
                        onClose: () => {
                            //关闭弹窗
                            open.value = false
                          //调用重新查询数据操作
                            emit('refreshDataList')
                        }
                    });

             })
        }else{
            //新增
            addSubject(form.value).then(resp=>{
                ElMessage.success({
                       message: '新增成功',
                       duration: 500,
                       onClose: () => {
                           //关闭弹窗
                           open.value = false
                         //调用重新查询数据操作
                           emit('refreshDataList')
                       }
                   });

             })
        }

      })

   };

   //对话框取消按钮
   const cancel = () => {
       open.value = false;
       resetFrom();
   };


   
// 上传图片时检查
function  beforeAvatarUpload(file) {
    console.log(file);
    //允许的图片类型
    const imgType = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif');
    //文件大小3M
    const imgLimit= (file.size / 1024 / 1024) < 3;
    if (!imgType) {
        ElMessage.error("只允许jpg、png、gif格式的图片");
        return false;
    }
    if (!imgLimit) {
        ElMessage.error("上传的图片大小不能超过3MB");
        return false;
    }

    return true;
}

/** 上传图片 */
function handleAvatarSuccess(res, file)  {
    console.log(res);
    form.value.imagePath=res.data;
};

   // 重置表单
   const resetFrom = () => {
       // 清空表单样式
       if (formRef.value){
           formRef.value.resetFields();
       }
       // 重置值
       form.value = {
           id: undefined,
           name: '',
           remark: '',
           imagePath: '',
           status: '0'
       };
   };

   //判断如果是修改操作，就要查询数据库，还原数据,要暴露出去
   const init = (id?: number) => {
    	open.value = true
   	// 重置表单数据
    resetFrom();
   	// id 存在则为修改
   	if (id) {
        getSubject(id).then(resp=> {
             const data:RespModel=resp.data;
             //转换为字符串{"id":1}
             const str=JSON.stringify(data);
             //再一次把字符串还原成对象
             form.value=JSON.parse(str);
             console.log(form.value)
             
        })
   	 }
   }

   //https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
   defineExpose({
   	init
   })

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
